<template>
  <a-card title="考核指标体系" style="margin-top:24px;">
    <a-table
      :columns="columns"
      :row-key="item => item.id"
      :data-source="dataSource"
      :loading="loading"
      bordered
    >
      <span slot="action" slot-scope="item">
        <a v-if="!item.isLeafNode">
          <a-popconfirm
            title="请选择新增类型"
            ok-text="新增条例目录"
            cancel-text="新增条例节点"
            @confirm="handleAddRegulation(item, 1)"
            @cancel="handleAddRegulation(item, 2)"
          >
            <a v-permission="`inspection:regulation:add`" href="#">新增</a>
          </a-popconfirm>
        </a>
        <template v-if="item.parentId">
          <a-divider type="vertical" />
          <a v-permission="`inspection:regulation:update`" href="#" @click="handleAddRegulation(item, 3)">修改</a>
          <a-divider type="vertical" />
          <a-popconfirm
            title="确认是否删除"
            ok-text="确认"
            cancel-text="取消"
            @confirm="handleDelete(item)"
          >
            <a v-permission="`inspection:regulation:del`" href="#" class="text-danger">删除</a>
          </a-popconfirm>
        </template>
      </span>
    </a-table>

    <!-- 新增/修改弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      width="900px"
      height="400px"
    >
      <a-form :form="form" layout="inline">
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="编号"
        >
          <a-input
            :disabled="type === 3"
            v-decorator="[
              'regulationNo',
              {
                rules: [{ required: true, message: '填写编号' }],
              },
            ]"
            placeholder="填写编号"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="条款名"
        >
          <a-input
            v-decorator="[
              'regulationName',
              {
                rules: [{ required: true, message: '填写条款名' }],
              },
            ]"
            placeholder="填写条款名"
          />
        </a-form-item>

        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="最高分"
        >
          <a-input
            v-decorator="[
              'highestScore',
              {
                rules: [{ required: true, message: '填写最高分' }],
              },
            ]"
            placeholder="填写最高分"
          />
        </a-form-item>

        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="最低分"
        >
          <a-input
            v-decorator="[
              'lowestScore',
              {
                rules: [{ required: true, message: '填写最低分' }],
              },
            ]"
            placeholder="填写最低分"
          />
        </a-form-item>

        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="考核类别"
        >
          <a-select
            v-decorator="[
              'inspectionType',
              { rules: [{ required: true, message: '请选择考核类别' }] },
            ]"
            @change="handleChange"
          >
            <a-select-option
              v-for="(item, index) in basicList"
              :key="item + '' + index"
              :value="item"
              >{{ item }}</a-select-option
            >
          </a-select>
        </a-form-item>

        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="执行部门"
        >
          <a-select mode="multiple" v-decorator="['executeDepts', { rules: [] }]">
            <a-select-option
              v-for="(item, index) in departmentList"
              :key="item.id + '' + index * 11"
              :value="item.id"
              >{{ item.deptName }}</a-select-option
            >
          </a-select>
        </a-form-item>

        <a-form-item
          style="width: 800px"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
          label="条款内容"
        >
          <a-textarea
            :rows="3"
            v-decorator="[
              'regulationContent',
              {
                rules: [{ required: true, message: '填写条款内容' }],
              },
            ]"
            placeholder="填写条款内容"
          />
        </a-form-item>

        <a-form-item
          style="width: 800px"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
          label="说明"
        >
          <a-textarea
            :rows="3"
            v-decorator="[
              'remark',
              {
                rules: [],
              },
            ]"
            placeholder="填写说明"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { basicService, inspectionService } from '@/services';

const columns = [
  {
    title: '编号',
    dataIndex: 'regulationNo',
    align: 'center',
    width: 200,
  },
  {
    title: '条款名',
    dataIndex: 'regulationName',
    key: 'regulationName',
    align: 'center',
    width: 150,
  },
  {
    title: '条款内容',
    dataIndex: 'regulationContent',
    key: 'regulationContent',
    align: 'center',
    minWidth: 150
  },
  {
    title: '说明',
    key: 'remark',
    dataIndex: 'remark',
    align: 'center',
  },
  {
    title: '最高分',
    key: 'highestScore',
    dataIndex: 'highestScore',
    align: 'center',
    width: 100,
  },
  {
    title: '最低分',
    key: 'lowestScore',
    dataIndex: 'lowestScore',
    align: 'center',
    width: 100,
  },
  {
    title: '考核类别',
    key: 'inspectionType',
    dataIndex: 'inspectionType',
    align: 'center',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    width: 200,
  },
];

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

export default {
  name: 'inspectionRegulation',

  data() {
    return {
      columns: columns,
      dataSource: [],
      loading: false,
      visible: false,
      type: 1, // 1-新增 2-修改
      formItemLayout,
      form: this.$form.createForm(this, { name: 'add_regulation' }),
      formParams: {},
      confirmLoading: false,
      departmentList: [],
      branchList: [],
      branchListDepartment: [],
      regulationList: [],
      basicList: [],
    };
  },

  computed: {
    modalTitle() {
      return this.type < 3 ? '新增' : '修改';
    },
  },

  created() {
    this.getDataTree();
    this.departmentQuery();
    this.typeQuery();
  },

  methods: {
    // 获取树形数据
    getDataTree() {
      inspectionService.getRegulationTree().then(res => {
        console.log(res);
        if (res.code === '200') {
          this.dataSource = [res.data.rootNode];
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 获取数据类型
    typeQuery() {
      inspectionService.getTypeList({}).then(res => {
        console.log(res);
        if (res.code === '200') {
          this.basicList = res.data.items;
        }
      });
    },

    // 获取部门数据
    departmentQuery() {
      basicService.getDeptList({ needDetail: true, canChoose: false }).then(res => {
        console.log(res);
        if (res.code === '200') {
          this.departmentList = res.data.items;
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 删除条例
    handleDelete(item) {
      inspectionService.regulationDel({ id: item.id }).then(() => {
        this.$message.success('删除条例成功');
        this.getDataTree();
      });
    },

    // 新增条例，修改条例
    handleAddRegulation(item, type) {
      console.log(item, type);
      this.formParams.parentId = item.id;
      this.type = type;
      this.formParams.isLeafNode = type === 1 ? 0 : 1; // type=1新增目录 type=2新增节点 type=3修改节点

      this.visible = true;
      if (type === 3) {
        this.getRegulation(item.id);
      }
    },

    // 获取详情
    getRegulation(id) {
      inspectionService.getRegulation({ id: id }).then(res => {
        setTimeout(() => {
          this.form.setFieldsValue({ ...res.data });
        }, 100);
      });
    },

    // 新建/修改条例确定
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          const params = {
            ...values,
            ...this.formParams,
          };
          console.log('form参数', { params });
          if (this.type === 1 || this.type === 2) {
            inspectionService
              .regulationSave(params)
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('新增条例成功');
                  this.visible = false;
                  this.getDataTree();
                  // 清空表单
                  this.form.resetFields();
                  this.formParams = {};
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          }

          if (this.type === 3) {
            params.id = this.formParams.parentId;
            inspectionService
              .regulationUpdate(params)
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('修改条例成功');
                  this.visible = false;
                  this.getDataTree();
                  // 清空表单
                  this.form.resetFields();
                  this.formParams = {};
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },

    // 取消新建条例
    handleCancel() {
      // 清空表单
      this.form.resetFields();
      this.formParams = {};
      this.visible = false;
    },

    // 选择支部
    handleChange(value) {
      console.log(value);
      this.branchList.map(item => {
        if (item.id === value) {
          this.branchListDepartment = item.departments;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.ant-modal-body {
  max-height: 800px;
  overflow-y: auto;
}
.ant-form-item {
  width: 400px;
}
</style>
<style lang="less"></style>
